<?php

namespace plugin\admin\app\controller;

use App\model\EmailCate;
use process\Monitor;
use support\Request;
use support\Response;
use plugin\admin\app\model\Email;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 邮件管理
 */
class EmailController extends Crud
{

    /**
     * @var Email
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Email;
    }

    protected function afterQuery($items)
    {
        $cate_data = EmailCate::query()->pluck('name', 'id')->toArray();
        var_dump($cate_data);
        foreach ($items as $item) {
            $item['cate_name'] = $cate_data[$item['cate']];
        }
        return $items;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('email/index');
    }

    public function getCates()
    {
        $data = EmailCate::query()->get()->toArray();
        return json(['code' => 0, 'msg' => '', 'data' => $data]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        $cate_data = $this->getCate();
        return view('email/insert', ['cate_data' => $cate_data]);
    }


    private function getCate()
    {
        $data = EmailCate::query()->get()->toArray();
        return $data;
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        $cate_data = $this->getCate();
        return view('email/update', ['cate_data' => $cate_data]);
    }

}
